let app = getApp()
const util = require('../../utils/util.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        configColorForOnlyStyle: app.globalData.configColorForOnlyStyle,
        configColor: app.globalData.configColor,
        showChooseTitle: false,
        columns: ['', '记一笔'],
        selectedColumnValue: '',
        youhaoNotice: '',
        oilDate: new Date().getTime(),
        oilDateShow: '',
        showOidTimePick: false,
        currentkm: '',
        lastkm: '',
        lastdanjia: '',
        resultPayTemp: '',
        isOilFull: true,
        isOilWarn: false,
        isOilRemark: true,
        danjiaTemp: '',
        youliangTemp: '',
        jixianMoneyTemp: '',
        lastIndexTemp: [],
        // groups: [ 
        //     { text: '不记录账单', value: 0 },     
        // ],
        showGroupIndex: 1,
        title: "将此次油费添加至账本?",
        updateOilId: 0,
        showUpdate: false,
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
    },
    go_index() {
        wx.switchTab({
            url: '/pages/index/index',
        });
    },

    onClose() {
        this.setData({
            showChooseTitle: false,
            showOidTimePick: false
        });
        let that = this
        setTimeout(function () {
            that.setData({
                columns: ['', '记一笔'],
            });
        }, 200);
    },

    onConfirmForOil(event) {
        this.setData({ showOidTimePick: false });
        this.setData({
            oilDate: event.detail,
            oilDateShow: util.formatTime(new Date(event.detail))
        });
    },

    openChooseTitle() {
        wx.request({
            url: app.globalData.url + '/getAllCarName',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                if (res.data.flag) {
                    let columnsTemp = this.data.columns
                    for (var i = 0; i < res.data.data.length; i++) {
                        if (res.data.data[i] != this.data.selectedColumnValue) {
                            columnsTemp.push(res.data.data[i])
                        }
                    }
                    this.setData({
                        columns: columnsTemp,
                        showChooseTitle: true
                    })
                } else {
                    wx.showToast({
                        title: '车牌查询失败，请稍后尝试',
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log('车牌查询失败，请稍后尝试!!!', err);
            }
        })
    },
    // 切换标题
    onChangeTitle(event) {
        const { picker, value, index } = event.detail;
        if (index == 1) {
            wx.redirectTo({
                url: '/pages/add_record/add_record'
            })
            return
        }
        this.showPage(value)
        this.onClose()
    },
    openOidTimePick() {
        this.setData({
            showOidTimePick: true
        })
    },
    changeFull(e) {
        if (e.currentTarget.dataset.isfull == 1) {
            this.setData({
                isOilFull: true
            })
        } else {
            this.setData({
                isOilFull: false
            })
        }
    },
    changeWarn(e) {
        if (e.currentTarget.dataset.iswarn == 1) {
            this.setData({
                isOilWarn: true
            })
        } else {
            this.setData({
                isOilWarn: false
            })
        }
    },
    changeMark(e) {
        if (e.currentTarget.dataset.ismark == 1) {
            this.setData({
                isOilRemark: true
            })
        } else {
            this.setData({
                isOilRemark: false
            })
        }
    },
    oilBlur(event) {
        // console.log(this.data.resultPayTemp > this.data.jixianMoneyTemp)
        if (this.data.resultPayTemp > this.data.jixianMoneyTemp) {
            this.setData({
                youhaoNotice: '注意: 实际支付金额大于了机显金额'
            })
        } else {
            this.setData({
                youhaoNotice: '油枪自动跳停, 才算"加满"。'
            })
        }
        // console.log(event.currentTarget.dataset.index)
        let currentIndex = event.currentTarget.dataset.index;
        let danjia = this.data.danjiaTemp
        let youliang = this.data.youliangTemp
        let jixianMoney = this.data.jixianMoneyTemp
        let resultPay = this.data.resultPayTemp

        let changeOne = 0;
        let lastIndex = this.data.lastIndexTemp
        if (lastIndex.length < 1 && danjia > 0) {
            lastIndex.push("1")
        }
        if (currentIndex == 1 && danjia > 0 || currentIndex == 2 && youliang > 0 || currentIndex == 3 && jixianMoney > 0) {
            lastIndex = lastIndex.filter(item => {
                return item != currentIndex
            })
            lastIndex.push(currentIndex)
        }
        this.setData({
            lastIndexTemp: lastIndex
        })
        changeOne = lastIndex[0]
        if (resultPay < 1 && jixianMoney > 0) {
            // 实付金额没填写,机显已填写
            this.setData({
                resultPayTemp: jixianMoney
            })
        }
        if (danjia > 0 && youliang > 0 && jixianMoney > 0) {

            if (changeOne == 1) {
                // 修改单价
                this.setData({
                    danjiaTemp: (jixianMoney / youliang).toFixed(2)
                })
            }
            if (changeOne == 2) {
                // 修改油量
                this.setData({
                    youliangTemp: (jixianMoney / danjia).toFixed(2)
                })
            }
            if (changeOne == 3) {
                // 修改机显金额
                this.setData({
                    jixianMoneyTemp: Math.floor((danjia * youliang) * 100) / 100
                })
            }

        }

        if (danjia > 0 && youliang > 0 && jixianMoney < 1) {
            // 单价和油量已填写,机显金额不存在
            this.setData({
                jixianMoneyTemp: Math.floor((danjia * youliang) * 100) / 100
            })
            lastIndex = lastIndex.filter(item => {
                return item != "3"
            })
            lastIndex.unshift("3")
            this.setData({
                lastIndexTemp: lastIndex
            })

            // console.log(null < 1)
            if (resultPay < 1) {
                // 实付金额没填写
                this.setData({
                    resultPayTemp: Math.floor((danjia * youliang) * 100) / 100
                })
            }
        }

        if (danjia > 0 && youliang < 1 && jixianMoney > 0) {
            // 单价和机显金额已填写,油量不存在
            this.setData({
                youliangTemp: (jixianMoney / danjia).toFixed(2)
            })

            lastIndex = lastIndex.filter(item => {
                return item != "2"
            })
            lastIndex.unshift("2")
            this.setData({
                lastIndexTemp: lastIndex
            })
        }

        if (danjia < 1 && youliang > 0 && jixianMoney > 0) {
            // 油量和机显金额已填写,单价不存在
            this.setData({
                danjiaTemp: (jixianMoney / youliang).toFixed(2)
            })

            lastIndex = lastIndex.filter(item => {
                return item != "1"
            })
            lastIndex.unshift("1")
            this.setData({
                lastIndexTemp: lastIndex
            })
        }

    },
    zonglicheng() {
        this.setData({
            youhaoNotice: '当前里程表显示的总里程'
        })
    },
    changeDropdown(value) {
        this.setData({
            showGroupIndex: value.detail
        })
    },
    // 提交表单
    submit(e) {
        let resultKM = e.detail.value.resultKM
        let danjia = e.detail.value.danjia
        let youliang = e.detail.value.youliang
        let jixianMoney = e.detail.value.jixianMoney
        let resultMoney = e.detail.value.resultMoney
        if (!resultKM || !danjia || !youliang || !jixianMoney || !resultMoney) {
            wx.showToast({
                title: '输入框不能为空',
                icon: 'error'
            })
            return
        }
        // console.log(this.data.isOilRemark)
        // console.log(this.data.isOilFull)
        // console.log(this.data.isOilWarn)
        wx.request({
            url: app.globalData.url + '/addorUpdateOil',
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                id: this.data.updateOilId,
                number: this.data.selectedColumnValue,
                userId: wx.getStorageSync('userInfo').id,
                oilTime: this.data.oilDateShow,
                total: this.data.currentkm,
                oilPrice: this.data.danjiaTemp,
                quantity: this.data.youliangTemp,
                machineMoney: this.data.jixianMoneyTemp,
                resultMoney: this.data.resultPayTemp,
                isFull: this.data.isOilFull,
                isWarn: this.data.isOilWarn,
                isRecord: this.data.isOilRemark,
                groupId: this.data.groups[this.data.showGroupIndex].groupId
            },
            success: (res) => {
                if (res.data.flag) {
                    wx.showToast({
                        title: '操作成功^_^',
                        icon: 'success'
                    })
                    wx.switchTab({
                        url: '/pages/oil/oil',
                    })
                } else {
                    wx.showToast({
                        title: '操作失败:' + res.data.message,
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })

    },

    showPage(value) {
        // 上一次总里程+上一次单价  
        var dateNow = new Date();
        this.setData({
            selectedColumnValue: value,
            oilDate: dateNow.getTime(),
            oilDateShow: util.formatTime(dateNow)
        })
        wx.request({
            url: app.globalData.url + '/getLastInfo',
            method: 'GET',
            data: {
                number: value,
            },
            success: (res) => {
                // console.log(res)
                if (res.data.flag) {
                    if (res.data.data) {
                        this.setData({
                            lastkm: res.data.data.total,
                            lastdanjia: res.data.data.oilPrice,
                            danjiaTemp: res.data.data.oilPrice
                        })
                    } else {
                        this.setData({
                            lastkm: 0,
                            lastdanjia: '0.00'
                        })
                    }

                }
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },
    getGroupByUser() {
        wx.request({
            url: app.globalData.url + '/getGroupByUser',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                if (res.data.flag) {
                    let groupList = [{ text: '-----不记录账单-----', value: 0, groupId: 0 }]
                    let list = res.data.data
                    let indexTemp = 1
                    list.forEach((item) => {
                        if (item.active != 2) {
                            return
                        }
                        let groupTemp = { text: '', value: 0, groupId: item.id }
                        groupTemp.text = item.name
                        groupTemp.value = indexTemp++
                        groupList.push(groupTemp)
                        if (item.choose == 1) {
                            this.setData({
                                showGroupIndex: groupTemp.value
                            })
                        }
                    })
                    this.setData({
                        groups: groupList
                    })
                }
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },
    /**
     * 生命周期函数--监听页面
     */
    onLoad: function (options) {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline']
        })
        this.getGroupByUser()
        if (options.number) {
            // 修改
            this.setData({
                showUpdate: true,
                updateOilId: options.oilId,
                selectedColumnValue: options.number,
                oilDateShow: options.oilTime,
                currentkm: options.total,
                danjiaTemp: options.oilPrice,
                youliangTemp: options.quantity,
                jixianMoneyTemp: options.machineMoney,
                resultPayTemp: options.resultMoney,
                isOilFull: JSON.parse(options.isFull),
                isOilWarn: JSON.parse(options.isWarn),
                isOilRemark: JSON.parse(options.isRecord),
            })
        } else {
            //新增
            this.showPage(options.selectedColumnValue);
        }
    },

    /**
     * 生命周期函数--监听页面显示请求数据
     */
    onShow: function () {
        if (wx.getStorageSync('configColor') !== this.data.configColor
            || wx.getStorageSync('configColorForOnlyStyle') !== this.data.configColorForOnlyStyle) {
            this.setData({ configColor: wx.getStorageSync('configColor') });
            this.setData({ configColorForOnlyStyle: wx.getStorageSync('configColorForOnlyStyle') });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})



